<template>
    <div>
        <el-row>
            <el-col :span="24" :style="{ height: clientHeight + 'px' }">
                <div class="drag" style="width: 100%; height: 30px"></div>
                <el-row>
                    <el-col
                        :span="12"
                        :style="{ height: clientHeight - 70 + 'px', display: 'flex', 'align-items': 'center' }"
                    >
                        <div
                            style="
                                padding: 0px 48px;
                                width: 100%;
                                height: 100%;
                                box-sizing: border-box;
                                display: flex;
                                flex-direction: column;
                                justify-content: center;
                            "
                        >
                            <div class="title" style="">允许控制本机</div>
                            <el-form :model="info" ref="local" :rules="rules">
                                <div style="margin-bottom: 8px">
                                    <div
                                        style="
                                            vertical-align: middle;
                                            font-size: 14px;
                                            color: #606266;
                                            line-height: 40px;
                                            padding: 2px 0 10px 0;
                                            box-sizing: border-box;
                                        "
                                    >
                                        本机识别码
                                    </div>
                                    <div style="">
                                        <div style="font-size: 22px; font-weight: bold; color: #409eff">
                                            {{ info.identifyCode | identifyCode }}
                                            <i
                                                class="el-icon-copy-document"
                                                style="margin-left: 10px; font-size: 18px; cursor: pointer"
                                                @click="clipboard"
                                            ></i>
                                        </div>
                                    </div>
                                </div>
                                <el-form-item label="本机验证码" style="margin-bottom: 20px" prop="validateCode">
                                    <el-input
                                        ref="validateCode"
                                        v-model="info.validateCode"
                                        placeholder="请输入验证码"
                                        @blur="handleBlur"
                                        v-if="editable"
                                    ></el-input>
                                    <div v-else style="font-size: 24px">
                                        <br />{{ info.validateCode
                                        }}<i
                                            class="el-icon-edit"
                                            style="margin-left: 20px; font-size: 18px; cursor: pointer"
                                            @click="handleEdit"
                                        ></i>
                                    </div>
                                </el-form-item>
                            </el-form>
                            <div style="height: 88px"></div>
                        </div>
                    </el-col>
                    <el-col
                        :span="12"
                        :style="{ height: clientHeight - 70 + 'px', display: 'flex', 'align-items': 'center' }"
                    >
                        <div
                            style="
                                padding: 0px 15px;
                                width: 100%;
                                height: 100%;
                                box-sizing: border-box;
                                display: flex;
                                flex-direction: column;
                                justify-content: center;
                            "
                        >
                            <div class="title">控制远程设备</div>
                            <el-form :model="ruleForm" ref="ruleForm">
                                <el-form-item label="伙伴识别码" style="margin-bottom: 8px">
                                    <el-input v-model="ruleForm.identifyCode" placeholder="请输入远程设备代码">
                                        <template slot="suffix" v-if="historyList && historyList.length > 0">
                                            <el-dropdown @command="chooseHistory" trigger="click">
                                                <i class="el-icon-arrow-down"></i>
                                                <el-dropdown-menu slot="dropdown">
                                                    <el-dropdown-item
                                                        v-for="(item, index) in historyList"
                                                        :key="index"
                                                        :command="item"
                                                    >
                                                        <div class="history-item">
                                                            {{ item.identifyCode }}
                                                            <i
                                                                class="el-icon-close"
                                                                @click.stop="deleteIt(item, index)"
                                                            ></i>
                                                        </div>
                                                    </el-dropdown-item>
                                                </el-dropdown-menu>
                                            </el-dropdown>
                                        </template>
                                    </el-input>
                                </el-form-item>
                                <el-form-item label="验证码" style="margin-bottom: 20px">
                                    <el-input v-model="ruleForm.validateCode" placeholder="请输入验证码"></el-input>
                                </el-form-item>
                                <el-form-item style="margin-bottom: 15px">
                                    <el-radio-group v-model="ruleForm.type">
                                        <el-radio :label="1">远程控制</el-radio>
                                        <el-radio :label="2" disabled>文件传输</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <div class="login-btn">
                                    <el-button type="primary" round size="medium" @click="handleConnect">
                                        远程协助
                                    </el-button>
                                </div>
                            </el-form>
                        </div>
                    </el-col>
                </el-row>
                <div style="font-size: 14px; display: flex; align-items: center; height: 40px">
                    <div
                        style="background: #f73131; width: 10px; height: 10px; border-radius: 50%; margin-left: 10px"
                        v-if="status == 0"
                    >
                        &nbsp;
                    </div>
                    <div style="margin-left: 10px" v-if="status == 0">离线中</div>
                    <div
                        style="background: #67c23a; width: 10px; height: 10px; border-radius: 50%; margin-left: 10px"
                        v-if="status == 1"
                    >
                        &nbsp;
                    </div>
                    <div style="margin-left: 10px" v-if="status == 1">连接准备已就绪(安全连接)</div>
                </div>
            </el-col>
        </el-row>
        <!-- <div class="more" :style="{ right: '1px'  }">
            <el-dropdown @command="handleCommand" trigger="click" placement="bottom">
                <i class="el-icon-setting" style="color: #000"></i>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item icon="el-icon-refresh" command="update">检查新版本</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div> -->
    </div>
</template>

<script>
import { ClientJS } from 'clientjs'
import io from 'socket.io-client'
const Store = require('electron-store')
const store = new Store()
let socket
export default {
    data() {
        return {
            clientHeight: 0,
            info: {},
            ruleForm: {
                identifyCode: '',
                validateCode: '',
                type: 1
            },
            historyList: [],
            editable: false,
            rules: {
                validateCode: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    { min: 6, max: 8, message: '长度在 6 到 8 个字符', trigger: 'blur' }
                ]
            },
            status: 0,
            userId: ''
        }
    },
    filters: {
        identifyCode(value) {
            if (value) {
                return value.substr(0, 3) + ' ' + value.substr(3, 3) + ' ' + value.substr(6, 3)
            }
            return value
        }
    },
    beforeMount() {
        this.clientHeight = document.documentElement.clientHeight || document.body.clientHeight
    },
    created() {
        localStorage.removeItem('Authorization')
        let historyStore = store.get('historyList')
        if (historyStore) {
            this.historyList = JSON.parse(JSON.stringify(historyStore))
        }
        //localStorage.clear()
        const client = new ClientJS()
        this.info = {
            identifyCode: localStorage.getItem('identifyCode') || '',
            validateCode: localStorage.getItem('validateCode') || ''
        }

        this.userId = this.info.identifyCode
        socket = io.connect(window.platform.socketioUrl + '?userId=' + this.userId)
        socket.on('connect', () => {
            console.log('connected to server')
            this.createDevice()
        })
        socket.on('disconnected', () => {
            console.log('disconnected with server')
        })
        socket.on('reconnect_error', error => {
            console.log('reconnect_error with server')
            this.reconnect()
        })
        socket.on('callRemote', data => {
            if (data.target.includes(this.userId)) {
                window.ipcRenderer.send('createAnswerWindow', {
                    from: this.userId,
                    to: data.source,
                    mark: data.mark
                })
            }
        })
    },
    methods: {
        handleCommand(command) {
            if (command === 'update') {
                window.ipcRenderer.sendSync('opennew', command)
            }
        },
        async createDevice() {
            const info = await window.ipcRenderer.invoke('getDeviceInfo')
            const client = new ClientJS()
            info.mac = client.getFingerprint()
            info.identifyCode = this.info.identifyCode
            this.$axios.post('auth/create', info).then(res => {
                if (res.data.code == 200) {
                    this.status = 1
                    this.info = res.data.data
                    localStorage.setItem('identifyCode', this.info.identifyCode)
                    localStorage.setItem('validateCode', this.info.validateCode)
                    localStorage.setItem('Authorization', res.data.data.accessToken)
                } else {
                    this.$message.error(res.data.message)
                }
            })
        },
        reconnect() {
            this.status = 0
        },
        handleConnect() {
            if (!this.ruleForm.identifyCode) {
                this.$message.error('请输入远程设备代码')
                return
            }
            if (!this.ruleForm.validateCode) {
                this.$message.error('请输入验证码')
                return
            }
            if (this.ruleForm.identifyCode == this.info.identifyCode) {
                this.$message.error('请输入非本机的识别码')
                return
            }
            if (this.status == 0) {
                this.$message.error('本机离线中')
                return
            }
            this.$axios.post('user/connect', this.ruleForm).then(res => {
                if (res.data.code == 200) {
                    window.ipcRenderer.send('createRemoteWindow', {
                        from: this.info.identifyCode,
                        to: this.ruleForm.identifyCode,
                        mark: Math.random().toString(36).slice(-6)
                    })
                    let flag = false
                    for (let i = 0; i < this.historyList.length; i++) {
                        if (this.historyList[i].identifyCode === this.ruleForm.identifyCode) {
                            flag = true
                        }
                    }
                    if (!flag) {
                        this.historyList.push({
                            identifyCode: this.ruleForm.identifyCode,
                            validateCode: this.ruleForm.validateCode,
                            type: 1
                        })
                        store.set('historyList', this.historyList)
                    }
                } else {
                    this.$message.error(res.data.message)
                }
            })
        },
        clipboard() {
            navigator.clipboard.writeText(this.info.identifyCode)
            this.$message.success('已复制')
        },
        chooseHistory(e) {
            this.ruleForm = JSON.parse(JSON.stringify(e))
        },
        deleteIt(item, index) {
            this.historyList.splice(index, 1)
        },
        handleBlur() {
            this.$refs.local.validate(valid => {
                if (valid) {
                    this.$axios
                        .post('user/updateValidateCode', {
                            validateCode: this.info.validateCode
                        })
                        .then(res => {
                            if (res.data.code == 200) {
                                this.editable = false
                                localStorage.setItem('validateCode', this.info.validateCode)
                            } else {
                                this.$message.error(res.data.message)
                            }
                        })
                } else {
                    return false
                }
            })
        },
        handleEdit() {
            this.editable = true
            this.$nextTick(() => {
                this.$refs.validateCode.focus()
            })
        }
    }
}
</script>

<style scoped>
::v-deep .el-form-item__label:before {
    content: '' !important;
    margin-right: 0px !important;
}
.title {
    font-size: 20px;
}

.history-item {
    position: relative;
    width: 265px;
}
.history-item .el-icon-close {
    position: absolute;
    right: 0;
    top: 11px;
}
.el-popper[x-placement^='bottom'] {
    margin-top: 5px;
}
.login-btn {
    text-align: center;
}
.login-btn button {
    width: 150px;
}
.more {
    position: fixed;
    top: 1px;
    width: 44px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
}
</style>
